<template>
  <div class="">
    <el-table :data="$store.state.list" border style="width: 800px">
      <el-table-column prop="id" label="编号" width="100"> </el-table-column>
      <el-table-column prop="title" label="标题"> </el-table-column>
      <el-table-column prop="author" label="作者"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="remove(scope.$index)">删除</el-button>
          <el-button @click="edit(scope.row, scope.$index)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="编辑" :visible.sync="show">
      <el-form :model="form">
        <el-form-item label="标题">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="form.author"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="update">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      show: false,
      //控制弹窗显示隐藏
      form: {
        title: "",
        author: "",
      },
      //编辑弹框的v-model
      editIndex: -1,
      //保存要编辑的下标
    };
  },
  mounted() {},
  methods: {
    remove(index) {
      this.$store.commit("remove", index);
    },
    //删除方法
    edit(row, index) {
      this.show = true; //让弹框出现
      this.form.title = row.title;
      this.form.author = row.author;
      //回填数据
      this.editIndex = index;
      //把编辑的这条数据的下标保存下来
    },
    //点击编辑按钮回填数据并保存下标
    update() {
      // this.$store.commit("update",)
      this.$store.state.list[this.editIndex].title = this.form.title;
      this.$store.state.list[this.editIndex].author = this.form.author;
      this.show = false;
    },
    //点击编辑弹框里的确定 （在这里偷懒了，没有传到vuex里操作，这种写法可以实现但是不规范）
  },
  components: {},
};
</script>

<style lang="scss"></style>
